"use strict";
const { Sequelize, DataTypes } = require("sequelize");
const sequelize = new Sequelize("officer", "postgres", "qq_112358", {
  host: "8.129.171.243",
  dialect:
    "postgres" /* 选择 'mysql' | 'mariadb' | 'postgres' | 'mssql' 其一 */,
});

function defineModel(seqInstance, name, attrs) {
  let objAttrs = {};
  objAttrs.id = {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
  };

  for (let p in attrs) {
    let value = attrs[p];
    if (typeof value === "object" && value["type"]) {
      value.allowNull = value.allowNull === undefined ? false : value.allowNull;
      objAttrs[p] = value;
    } else {
      objAttrs[p] = {
        type: value,
        allowNull: false,
      };
    }
  }
  objAttrs.createdAt = {
    type: DataTypes.BIGINT,
    allowNull: false,
  };
  objAttrs.updatedAt = {
    type: DataTypes.BIGINT,
    allowNull: false,
  };
  objAttrs.version = {
    type: DataTypes.BIGINT,
    allowNull: false,
  };
  objAttrs.remarks = {
    type: DataTypes.STRING(800),
    allowNull: true,
  };

  let User = seqInstance.define(name, objAttrs, {
    tableName: name,
    timestamps: false,
    hooks: {
      beforeValidate: function (obj) {
        let now = Date.now();
        if (obj.isNewRecord) {
          obj.createdAt = now;
          obj.updatedAt = now;
          obj.version = 0;
        } else {
          obj.updatedAt = now;
          obj.version += 1;
        }
      },
    },
  });
  return User;
}

let obj = {
  sequelize: sequelize,
  defineModel: defineModel,
  DataTypes:DataTypes
};

module.exports = obj;
